<template>
  <div class="bg-white rounded-lg shadow-sm p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-900 mb-2">服务数据</h1>
      <p class="text-gray-500">查看您的服务统计数据和历史记录</p>
    </div>

    <div class="flex items-center gap-2 mb-6">
      <span class="text-sm text-gray-700">时间范围:</span>
      <select class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"><option>最近30天</option><option>最近7天</option><option>最近90天</option><option>自定义</option></select>
    </div>

    <div class="grid grid-cols-3 gap-6 mb-8">
      <div class="bg-gray-50 rounded-lg p-6">
        <div class="text-sm text-gray-600 mb-2">已完成订单</div>
        <div class="text-3xl font-bold text-gray-900 mb-2">{{ stats.completedOrders }}</div>
        <div class="flex items-center gap-1 text-sm text-green-600">
          <span>完成率 {{ stats.completionRate }}%</span>
        </div>
      </div>
      <div class="bg-gray-50 rounded-lg p-6">
        <div class="text-sm text-gray-600 mb-2">平均评分</div>
        <div class="text-3xl font-bold text-gray-900 mb-2">{{ stats.avgRating }}</div>
      </div>
      <div class="bg-gray-50 rounded-lg p-6">
        <div class="text-sm text-gray-600 mb-2">总收入</div>
        <div class="text-3xl font-bold text-gray-900 mb-2">¥{{ stats.totalIncome.toFixed(2) }}</div>
        <div class="flex items-center gap-1 text-sm text-green-600">
          <span>本月收入 ¥{{ stats.monthIncome.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <div class="mb-8">
      <h2 class="text-lg font-semibold text-gray-900 mb-4">订单趋势</h2>
      <div class="bg-gray-50 rounded-lg p-6">
        <div class="h-64"><canvas id="orderTrendChart"></canvas></div>
      </div>
    </div>

    <div>
      <h2 class="text-lg font-semibold text-gray-900 mb-4">最近接单记录</h2>
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-gray-200">
              <th class="text-left py-3 px-4 text-sm font-medium text-gray-700">订单号</th>
              <th class="text-left py-3 px-4 text-sm font-medium text-gray-700">服务内容</th>
              <th class="text-left py-3 px-4 text-sm font-medium text-gray-700">下单人</th>
              <th class="text-left py-3 px-4 text-sm font-medium text-gray-700">完成时间</th>
              <th class="text-left py-3 px-4 text-sm font-medium text-gray-700">收入</th>
              <th class="text-left py-3 px-4 text-sm font-medium text-gray-700">评分</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="order in recentOrders"
              :key="order.id"
              class="border-b border-gray-100 hover:bg-gray-50"
            >
              <td class="py-4 px-4 text-sm text-gray-900">{{ order.id }}</td>
              <td class="py-4 px-4 text-sm text-gray-700">{{ order.title }}</td>
              <td class="py-4 px-4 text-sm text-gray-700">{{ order.orderer }}</td>
              <td class="py-4 px-4 text-sm text-gray-700">{{ order.completedAt }}</td>
              <td class="py-4 px-4 text-sm text-green-600 font-medium">¥{{ order.fee }}</td>
              <td class="py-4 px-4 text-sm text-gray-700">{{ order.ratingText }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'CourierData',
  data() {
    return {
      stats: {
        completedOrders: 0,
        avgRating: '0.0',
        completionRate: 0,
        totalIncome: 0,
        monthIncome: 0
      },
      recentOrders: []
    }
  },
  methods: {
    async loadPerformance() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const { data } = await axios.get(`/api/couriers/performance/${userId}`)
        const s = (data && data.data) || {}
        this.stats.completedOrders = s.completedOrders || 0
        this.stats.avgRating = s.avgRating || '0.00'
        this.stats.completionRate = s.completionRate || 0
        this.stats.totalIncome = s.totalIncome || 0
        this.stats.monthIncome = s.monthIncome || 0
      } catch (e) {
        console.error('加载绩效数据失败', e)
      }
    },
    async loadRecentOrders() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const { data } = await axios.get(`/api/orders/courier/${userId}`)
        const list = (data && data.data) || []
        this.recentOrders = list
          .filter(o => o.status === 5 || o.status === '5')
          .sort((a, b) => new Date(b.completed_at || b.delivered_at || b.created_at) - new Date(a.completed_at || a.delivered_at || a.created_at))
          .slice(0, 5)
          .map(o => ({
            id: o.id,
            title: '快递代拿',
            orderer: o.user_nickname || `用户${String(o.order_user_info || '').slice(-4)}`,
            completedAt: (o.completed_at || o.delivered_at || o.created_at || '').replace('T', ' ').slice(0, 19),
            fee: Number(o.final_fee || o.suggested_fee || 0).toFixed(2),
            ratingText: (o.orderer_credit || '') ? `${o.orderer_credit}分` : ''
          }))
      } catch (e) {
        console.error('加载最近订单失败', e)
      }
    },
    initChart() {
      const ensureChartJs = () => new Promise((resolve) => {
        if (window.Chart) return resolve()
        const s = document.createElement('script')
        s.src = 'https://cdn.jsdelivr.net/npm/chart.js'
        s.onload = () => resolve()
        document.body.appendChild(s)
      })
      ensureChartJs().then(() => {
        const el = document.getElementById('orderTrendChart')
        if (!el) return
        const ctx = el.getContext('2d')
        // 暂时使用示例数据，后续可接真实趋势接口
        new window.Chart(ctx, {
          type: 'line',
          data: {
            labels: ['1月','2月','3月','4月','5月','6月','7月'],
            datasets: [{
              label: '订单数量',
              data: [5, 12, 18, 25, 32, 38, 45],
              borderColor: '#3B82F6',
              backgroundColor: 'rgba(59,130,246,0.1)',
              tension: 0.4,
              fill: true,
              pointRadius: 4,
              pointBackgroundColor: '#3B82F6',
              pointBorderColor: '#fff',
              pointBorderWidth: 2
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
              y: { beginAtZero: true, grid: { color: '#F3F4F6' } },
              x: { grid: { display: false } }
            }
          }
        })
      })
    }
  },
  mounted() {
    this.loadPerformance()
    this.loadRecentOrders()
    this.initChart()
  }
}
</script>
